package me.jessyan.mvparms.demo.mvp.ui.fragment;

import android.annotation.SuppressLint;

import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import android.widget.TextView;


import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.nianlun.libserialport.UsbSerialPortController;
import com.nianlun.libserialport.UsbSerialPortParameters;
import com.nianlun.libserialport.usbdriver.HexDump;
import com.nianlun.libserialport.usbdriver.UsbSerialPort;
import com.platform.ai.control.R;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;


import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


import butterknife.BindView;
import me.jessyan.mvparms.demo.di.component.DaggerUserComponent;
import me.jessyan.mvparms.demo.di.module.UserModule;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.entity.Device;
import me.jessyan.mvparms.demo.mvp.model.entity.MessageEvent;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import me.jessyan.mvparms.demo.mvp.model.logic.TextUtil;
import me.jessyan.mvparms.demo.mvp.presenter.UserPresenter;

import me.jessyan.mvparms.demo.mvp.ui.adapter.LightMainAdapter;
import me.jessyan.mvparms.demo.mvp.ui.holder.ItemClickListener;
import me.jessyan.mvparms.demo.util.HEX16String;
import me.jessyan.mvparms.demo.util.SpeechUtils;
import me.jessyan.mvparms.demo.util.USBRsUtils;
import retrofit2.http.HEAD;


@SuppressLint("ValidFragment")
public class LightFragment extends BaseFragment<UserPresenter> implements UserContract.View, SwipeRefreshLayout.OnRefreshListener, UsbSerialPortController.OnUsbSerialListener {


    @BindView(R.id.rv)
    RecyclerView mRv;

    private LightMainAdapter mainAdapter;
    private List<Device> mDevices = new ArrayList<>();

    private UsbSerialPortController mUsbSerialPortController;
    private UsbSerialPort mUsbSerialPort;


    public static LightFragment newInstance() {
        LightFragment fragment = new LightFragment();
        return fragment;
    }

    public LightFragment(){

    }

    @Override
    public void onResume() {
        super.onResume();
        if(getUserVisibleHint()){

        }
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userModule(new UserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_light, container, false);
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        initRecycleView();
        mDevices.clear();
        //0.廊灯，1.排风扇，2.镜前灯，3.浴室灯，4.明亮，5.观影，6.阅读，7.睡眠
        mDevices.add(new Device("廊灯",R.mipmap.corridor_off,0));
        mDevices.add(new Device("排风扇",R.mipmap.fan_off,0));
        mDevices.add(new Device("镜前灯",R.mipmap.mirror_off,0));
        mDevices.add(new Device("浴室灯",R.mipmap.bath_off,0));
        mDevices.add(new Device("明亮",R.mipmap.icon_light_model_unselect,0));
        mDevices.add(new Device("观影",R.mipmap.icon_video_model_unselect,0));
        mDevices.add(new Device("阅读",R.mipmap.icon_read_model_unselect,0));
        mDevices.add(new Device("睡眠",R.mipmap.icon_sleep_model_unselect,0));
        mainAdapter.notifyDataSetChanged();
        //初始化
        USBRsUtils.getInstance().init(getActivity(),this);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().getDispatcher();
    }

    private void initRecycleView() {
        mainAdapter = new LightMainAdapter(mDevices, new ItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                switchDevice(position,mDevices.get(position).getState() == 0);
            }
        });
        mRv.setAdapter(mainAdapter);
        ArmsUtils.configRecycleView(mRv, new GridLayoutManager(getContext(),3));
    }


    private void switchDevice(int position,boolean turnOn){
        switch (position){
            //0.廊灯，1.排风扇，2.镜前灯，3.浴室灯，4.明亮，5.观影，6.阅读，7.睡眠
            case 0:
                if(turnOn){
                    mDevices.get(0).setIcon(R.mipmap.corridor_on);
                    mDevices.get(0).setState(1);
                }else{
                    mDevices.get(0).setIcon(R.mipmap.corridor_off);
                    mDevices.get(0).setState(0);
                }
                break;
            case 1:
                if(turnOn){
                    mDevices.get(1).setIcon(R.mipmap.fan_turn);
                    mDevices.get(1).setState(1);
                }else{
                    mDevices.get(1).setIcon(R.mipmap.fan_off);
                    mDevices.get(1).setState(0);
                }
                break;
            case 2:
                if(turnOn){
                    mDevices.get(2).setIcon(R.mipmap.mirror_on);
                    mDevices.get(2).setState(1);
                }else{
                    mDevices.get(2).setIcon(R.mipmap.mirror_off);
                    mDevices.get(2).setState(0);
                }
                break;
            case 3:
                if(turnOn){
                    mDevices.get(3).setIcon(R.mipmap.bath_on);
                    mDevices.get(3).setState(1);
                }else{
                    mDevices.get(3).setIcon(R.mipmap.bath_off);
                    mDevices.get(3).setState(0);
                }
                break;
            case 4://明亮
                if(turnOn){
                    mDevices.get(4).setIcon(R.mipmap.icon_light_model_select);
                    mDevices.get(4).setState(1);
                }else{
                    mDevices.get(4).setIcon(R.mipmap.icon_light_model_unselect);
                    mDevices.get(4).setState(0);
                }
                break;
            case 5://观影
                if(turnOn){
                    mDevices.get(5).setIcon(R.mipmap.icon_video_model_select);
                    mDevices.get(5).setState(1);
                }else{
                    mDevices.get(5).setIcon(R.mipmap.icon_video_model_unselect);
                    mDevices.get(5).setState(0);
                }
                break;
            case 6://阅读
                if(turnOn){
                    mDevices.get(6).setIcon(R.mipmap.icon_read_model_select);
                    mDevices.get(6).setState(1);
                }else{
                    mDevices.get(6).setIcon(R.mipmap.icon_read_model_unselect);
                    mDevices.get(6).setState(0);
                }
                break;
            case 7://睡眠
                if(turnOn){
                    mDevices.get(7).setIcon(R.mipmap.icon_sleep_model_select);
                    mDevices.get(7).setState(1);
                }else{
                    mDevices.get(7).setIcon(R.mipmap.icon_sleep_model_unselect);
                    mDevices.get(7).setState(0);
                }
                break;
        }
        mainAdapter.notifyDataSetChanged();
        USBRsUtils.getInstance().sendUSBLightCommand(position, turnOn);
    }

    private void switchAllOpen(){
        mDevices.get(0).setIcon(R.mipmap.corridor_on);
        mDevices.get(0).setState(1);
        mDevices.get(1).setIcon(R.mipmap.mainlight_on);
        mDevices.get(1).setState(1);
        mDevices.get(2).setIcon(R.mipmap.other_on);
        mDevices.get(2).setState(1);
        mDevices.get(3).setIcon(R.mipmap.mirror_on);
        mDevices.get(3).setState(1);
        mDevices.get(4).setIcon(R.mipmap.bath_on);
        mDevices.get(4).setState(1);
        mDevices.get(5).setIcon(R.mipmap.switch_on);
        mDevices.get(5).setState(1);
    }

    private void switchAllClose(){
        mDevices.get(0).setIcon(R.mipmap.corridor_off);
        mDevices.get(0).setState(0);
        mDevices.get(1).setIcon(R.mipmap.mainlight_off);
        mDevices.get(1).setState(0);
        mDevices.get(2).setIcon(R.mipmap.other_off);
        mDevices.get(2).setState(0);
        mDevices.get(3).setIcon(R.mipmap.mirror_off);
        mDevices.get(3).setState(0);
        mDevices.get(4).setIcon(R.mipmap.bath_off);
        mDevices.get(4).setState(0);
        mDevices.get(5).setIcon(R.mipmap.switch_off);
        mDevices.get(5).setState(0);
    }
    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {

    }


    @Override
    public void showLoading() {

    }


    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        if (!message.isEmpty()) {

        }
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {

    }

    @Override
    public void killMyself() {
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void setAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void loginReturn(User user) {

    }

    @Override
    public void logout() {

    }


    public void uploadResult(String string) {

    }

    @Override
    public void onRefresh() {

    }

    @Subscriber
    public void onMessageEvent(MessageEvent event) {
        Log.i("lzd","语音返回："+event.getMessage());
        //0.廊灯，1.排风扇，2.镜前灯，3.浴室灯，4.明亮，5.观影，6.阅读，7.睡眠
        if(TextUtil.checkContains(event.getMessage(),new String[]{"打","开"})){
            if(TextUtil.checkContains(event.getMessage(),new String[]{"廊","灯"})){ ;
                switchDevice(0,true);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(0,true);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"排","风","扇"})){
                switchDevice(1,true);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(1,true);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"镜","前","灯"})){
                switchDevice(2,true);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(2,true);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"浴","室","灯"})){
                switchDevice(3,true);
                USBRsUtils.getInstance().sendUSBLightCommand(3,true);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(3,true);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"明","亮"})){
                switchDevice(4,true);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(4,true);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"观","影"})){
                switchDevice(5,true);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(5,true);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"阅","读"})){
                switchDevice(6,true);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(6,true);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"睡","眠"})){
                switchDevice(7,true);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(7,true);
            }
        }else if(TextUtil.checkContains(event.getMessage(),new String[]{"关","闭"})){
            if(TextUtil.checkContains(event.getMessage(),new String[]{"廊","灯"})){ ;
                switchDevice(0,false);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(0,false);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"排","风","扇"})){
                switchDevice(1,false);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(1,false);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"镜","前","灯"})){
                switchDevice(2,false);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(2,false);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"浴","室","灯"})){
                switchDevice(3,false);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(3,false);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"明","亮"})){
                switchDevice(4,false);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(4,false);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"观","影"})){
                switchDevice(5,false);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(5,false);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"阅","读"})){
                switchDevice(6,false);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(6,false);
            }else if(TextUtil.checkContains(event.getMessage(),new String[]{"睡","眠"})){
                switchDevice(7,false);
                SpeechUtils.getInstance(mContext).speakText("指令发送成功");
                USBRsUtils.getInstance().sendUSBLightCommand(7,false);
            }
        }
//        else if(TextUtil.checkContains(event.getMessage(),new String[]{"全","开"})){
//            switchAllOpen();
//            SpeechUtils.getInstance(mContext).speakText("指令发送成功");
//            USBRsUtils.getInstance().sendUSBLightCommand(5,true);
//        }else if(TextUtil.checkContains(event.getMessage(),new String[]{"全","关"})){
//            switchAllClose();
//            SpeechUtils.getInstance(mContext).speakText("指令发送成功");
//            USBRsUtils.getInstance().sendUSBLightCommand(5,false);
//        }
        mainAdapter.notifyDataSetChanged();

    }

    //485接口回调
    @Override
    public void onUsbDeviceStateChange(int usbDeviceState, UsbDevice usbDevice) {
        //状态改变
    }

    @Override
    public void onSerialOpenSuccess() {
       //串口链接成功
    }

    @Override
    public void onSerialOpenException(Exception e) {
       //串口链接失败
    }

    @Override
    public void onReceivedData(byte[] data) {
        //数据发送回调
        String receivedData;
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : data) {
            stringBuilder.append((int) b).append(" ");
        }
        receivedData = stringBuilder.toString();
    }

    @Override
    public void onSendException(Exception e) {
        //数据发送失败

    }


}
